<?php


class Controller_User extends Controller{


    public function action_index(){

        $logged = Auth::instance()->logged_in();


        if ($logged){
            $this->request->redirect('user/protected_content');
        }
        else{
            $this->request->redirect('user/form_sign_in');
        }
        
    }


    public function action_form_sign_in(){
        $this->request->response = View::factory('form_sign_in');
    }


    public function action_sign_in(){

        //$user = new Model_User;

        $username = $_POST['username'];
        $password = $_POST['password'];
        $logged = Auth::instance()->login($username, $password);


        if ($logged){
            $this->request->redirect('user/protected_content');
        }
        else{
            $this->request->response = View::factory('form_sign_in')
                                        ->set('message', 'could not authenticate user');
        }
        
    }


    public function action_form_sign_up(){
        $this->request->response = View::factory('form_sign_up');
    }

    public function action_sign_out(){
        Auth::instance()->logout();
        $this->request->redirect('user/form_sign_in');
    }

    public function action_sign_up(){

        $user = new Model_User;
        
	
        
        $user->username         = Arr::get( $_POST, 'username');
        $user->password         = Arr::get( $_POST, 'password');
        $user->password_confirm = Arr::get( $_POST, 'password_confirm');
        $user->email            = Arr::get( $_POST, 'email');


        if (!$user->check()){
            $this->request->response = View::factory('form_sign_up')
                                        ->set('error_message', 'could not sign up');
	    	echo "<pre>";	
	    	print_r($user->get_errors());
        }
        else{

            $user->save();
            $role = new Model_Role;
            $role->where('name', '=', 'login')->find();

            $res = $user->add('roles', $role);

            if ($res){
                $this->request->response = View::factory('form_sign_in')
                                            ->set('message', 'successfully registered');
            }
            else{
                $this->request->response = View::factory('form_sign_up')
                                            ->set('error_message', 'could not sign up');
            }
        }

    }



    public function action_protected_content(){

        $logged = Auth::instance()->logged_in();
        
        if ($logged){
            $this->request->response = View::factory('protected_content');
        }
        else{
            $this->request->redirect('user/form_sign_in');
        }
        
    }


    
}
?>
